#include <iostream>
#include <string>
#include <signal.h>
#include "../comm/httplib.h"
#include "oj_control.hpp"

using namespace httplib;
using namespace ns_control;

static Control* ctrptr=nullptr;

void handler(int sign)
{
    ctrptr->BackOnline();
}

int main(int argc, char *argv[])
{
    signal(SIGQUIT,handler);
    if (argc != 2)
    { 
        std::cout << "./a.out port" << std::endl;
        return 0;
    }
    Server svr;
    Control ctr;

    ctrptr=&ctr;
    // 获取全部的题目
    svr.Get("/all_questions", [&ctr](const Request &req, Response &resp)
            {
                std::string html;
                ctr.AllQuestions(&html);
                 resp.set_content(html, "text/html;charset=utf-8");
                  });
    // 获得单个题目
    svr.Get(R"(/question/(\d+))", [&ctr](const Request &req, Response &resp)
            {
        std::string number=req.matches[1];
        std::string html;
        ctr.OneQuestion(number,&html);
        resp.set_content(html,"text/html;charset=utf-8"); });
    // 判题
    svr.Post(R"(/judge/(\d+))", [&ctr](const Request &req, Response &resp)
             {
                 std::string number = req.matches[1];
                 std::string result_json;
                 ctr.Judge(number, req.body, &result_json);
                 resp.set_content(result_json, "text/json;charset=utf-8");
                 // resp.set_content("判断第"+num+"个题目","text/plain;charset=utf-8");
             });
    svr.set_base_dir("./wwwroot");

    svr.listen("0.0.0.0", atoi(argv[1]));
    return 0;
}